const { addItem } = require("./../shutdowns.js");
const chokidar = require('chokidar');
const { removeDuplicatesAndEmpty } = require('./../util/common.js');
const { joinPaths } = require('./../util/file.js');
const { parseM3u8File } = require('./../util/m3u8.js');

const confing = {};

function init(conf) {
    let watcherPaths = conf.watcherPaths || [];;
    if (conf.watcherWorkPath) {
        const curWorkPath = process.cwd();
        watcherPaths.push(curWorkPath);
    }

    watcherPaths = joinPaths(removeDuplicatesAndEmpty(watcherPaths));
    if (watcherPaths.length == 0) {
        console.info("未指定监控路径，程序退出");
        return;
    }

    console.info(`final watch len:${watcherPaths.length}, paths:[${watcherPaths}]`);
    const watcher = chokidar.watch(watcherPaths, {
        ignored: /(^|[\/\\])\../, // 忽略隐藏文件
        recursive: true, // 递归监视子目录
        persistent: true, // 保持监听状态
        ignoreInitial: true, // 忽略启动时的初始事件
        followSymlinks: true, // 跟踪符号链接指向的实际路径
    });
    confing.watcher = watcher;
    addItem(watcher);
    watcher
        .on('add', filePath => {
            console.log(`File ${filePath} has been added ${path.basename(filePath)} ::: ${path.extname(filePath)}`);
            let extname = path.extname(filePath);
            if (conf.addWatchers.includes(extname)) {
                parserFile(filePath);
            }
        })
        .on('change', filePath => {
            console.log(path.basename(filePath) + "" + path.extname(filePath));
            console.log(`File ${filePath} has been changed ${path.basename(filePath)}.${path.extname(filePath)}`);
        })
        .on('unlink', filePath => console.log(`File ${filePath} has been removed`))
        // .on('addDir', filePath => console.log(`File ${filePath} has been addDir`))
        // .on('unlinkDir', filePath => console.log(`File ${filePath} has been unlinkDir`))
        .on('ready', () => console.log(`File paths:[${watcherPaths}] ready done`))
        .on('error', filePath => console.log(`File ${filePath} has been error`));
    return watcher;
}

function close(watcher) {
    // 关闭监听器
    watcher.close();
}


module.exports = { init, close }